using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using CoachingOrganizer.Logic.Models.Tools.MoneyCalculation;
using CoachingOrganizer.Android.Helpers;
using CoachingOrganizer.Android.Adapters.Tools.MoneyCalculation;

namespace CoachingOrganizer.Android.Activities.Tools.MoneyCalculation
{
    [Activity(Label = "@string/ApplicationName")]
    public class MoneyCalculationDetailsActivity : Activity
    {
        private MoneyCalculationModel _model;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            _model = UIHelper.GetActivityModel<MoneyCalculationModel>(this, bundle);
            _model.Report.CurrentPeriodReportChanged += Report_CurrentPeriodReportChanged;
            SetContentView(Resource.Layout.MoneyCalculationDetailsLayout);
            InitLayout();
            Init();
            HookModel();
        }

        protected override void OnResume()
        {
            base.OnResume();
            //HookModel();
        }

        protected override void OnPause()
        {
            base.OnPause();
            //UnhookModel();
        }

        private void InitLayout()
        {
            TabHost moneyCalculationtabHost = FindViewById<TabHost>(Resource.Id.moneyCalculationTabHost);
            moneyCalculationtabHost.Setup();
            TabHost.TabSpec spec = moneyCalculationtabHost.NewTabSpec("tab1");
            spec.SetContent(Resource.Id.incomesTabsLinearLayout);
            spec.SetIndicator(Resources.GetString(Resource.String.MoneyCalculationIncomes));
            moneyCalculationtabHost.AddTab(spec);
            spec = moneyCalculationtabHost.NewTabSpec("tab2");
            spec.SetContent(Resource.Id.spentsLinearLayout);
            spec.SetIndicator(Resources.GetString(Resource.String.MoneyCalculationSpents));
            moneyCalculationtabHost.AddTab(spec);
            spec = moneyCalculationtabHost.NewTabSpec("tab3");
            spec.SetContent(Resource.Id.resultsLinearLayout);
            spec.SetIndicator(Resources.GetString(Resource.String.MoneyCalculationResults));
            moneyCalculationtabHost.AddTab(spec);
            spec = moneyCalculationtabHost.NewTabSpec("tab4");
            spec.SetContent(Resource.Id.plansLinearLayout);
            spec.SetIndicator(Resources.GetString(Resource.String.MoneyCalculationPlans));
            moneyCalculationtabHost.AddTab(spec);
        }

        private async void Init()
        {
            using (System.Threading.CancellationTokenSource cancellation = new System.Threading.CancellationTokenSource())
                await _model.LoadMoneyFlowItemsAsync(cancellation.Token);
        }

        private void HookModel()
        {
            HookModelToIncomesTab();
            HookModelToSpentsTab();
            HookModelToResultsTab();
        }

        private void HookModelToIncomesTab()
        {
            TabHost moneyCalculationIncomesTabHost = FindViewById<TabHost>(Resource.Id.moneyCalculationIncomesTabHost);
            moneyCalculationIncomesTabHost.Setup();
            TabHost.TabSpec spec = moneyCalculationIncomesTabHost.NewTabSpec("sub1tab1");
            spec.SetContent(Resource.Id.stableIncomesLinearLayout);
            spec.SetIndicator(Resources.GetString(Resource.String.StableIncomesOrSpents));
            moneyCalculationIncomesTabHost.AddTab(spec);
            spec = moneyCalculationIncomesTabHost.NewTabSpec("sub1tab2");
            spec.SetContent(Resource.Id.occasionalIncomesLinearLayout);
            spec.SetIndicator(Resources.GetString(Resource.String.OccasionalIncomesOrSpents));
            moneyCalculationIncomesTabHost.AddTab(spec);
            LinearLayout stableIncomesLinearLayout = FindViewById<LinearLayout>(Resource.Id.stableIncomesLinearLayout);
            ListView stableIncomesListView = FindViewById<ListView>(Resource.Id.stableIncomesListView);
            stableIncomesListView.Adapter = new StableIncomesAdapter(this, _model);
            AutoCompleteTextView stableIncomesItemNameTextView = FindViewById<AutoCompleteTextView>(Resource.Id.stableIncomesItemNameTextView);
            _model.Incomes.NewStableMoneyFlowItemNameChanged += (sender, e) => stableIncomesItemNameTextView.Text = _model.Incomes.NewStableMoneyFlowItemName;
            stableIncomesItemNameTextView.Adapter = new MoneyFlowItemNameSuggestionsAdapter(this, _model.Incomes, forStableItems: true);
            Button addStableIncomesItemButton = FindViewById<Button>(Resource.Id.addStableIncomesItemButton);
            addStableIncomesItemButton.Click += (sender, e) => _model.AddNewStableIncome(stableIncomesItemNameTextView.Text);
            ListView occasionalIncomesListView = FindViewById<ListView>(Resource.Id.occasionalIncomesListView);
            occasionalIncomesListView.Adapter = new OccasionalIncomesAdapter(this, _model);
            AutoCompleteTextView occasionalIncomesItemNameTextView = FindViewById<AutoCompleteTextView>(Resource.Id.occasionalIncomesItemNameTextView);
            _model.Incomes.NewOccasionalMoneyFlowItemNameChanged += (sender, e) => occasionalIncomesItemNameTextView.Text = _model.Incomes.NewOccasionalMoneyFlowItemName;
            occasionalIncomesItemNameTextView.Adapter = new MoneyFlowItemNameSuggestionsAdapter(this, _model.Incomes, forStableItems: false);
            Button addOccasionalIncomesItemButton = FindViewById<Button>(Resource.Id.addOccasionalIncomesItemButton);
            addOccasionalIncomesItemButton.Click += (sender, e) => _model.AddNewOccasionalIncome(occasionalIncomesItemNameTextView.Text);
        }

        private void HookModelToSpentsTab()
        {
            TabHost moneyCalculationSpentsTabHost = FindViewById<TabHost>(Resource.Id.moneyCalculationSpentsTabHost);
            moneyCalculationSpentsTabHost.Setup();
            TabHost.TabSpec spec = moneyCalculationSpentsTabHost.NewTabSpec("sub2tab1");
            spec.SetContent(Resource.Id.occasionalSpentsLinearLayout);
            spec.SetIndicator(Resources.GetString(Resource.String.OccasionalIncomesOrSpents));
            moneyCalculationSpentsTabHost.AddTab(spec);
            spec = moneyCalculationSpentsTabHost.NewTabSpec("sub2tab2");
            spec.SetContent(Resource.Id.stableSpentsLinearLayout);
            spec.SetIndicator(Resources.GetString(Resource.String.StableIncomesOrSpents));
            moneyCalculationSpentsTabHost.AddTab(spec);
            LinearLayout stableSpentsLinearLayout = FindViewById<LinearLayout>(Resource.Id.stableSpentsLinearLayout);
            ListView stableSpentsListView = FindViewById<ListView>(Resource.Id.stableSpentsListView);
            stableSpentsListView.Adapter = new StableSpentsAdapter(this, _model);
            AutoCompleteTextView stableSpentsItemNameTextView = FindViewById<AutoCompleteTextView>(Resource.Id.stableSpentsItemNameTextView);
            _model.Spents.NewStableMoneyFlowItemNameChanged += (sender, e) => stableSpentsItemNameTextView.Text = _model.Spents.NewStableMoneyFlowItemName;
            stableSpentsItemNameTextView.Adapter = new MoneyFlowItemNameSuggestionsAdapter(this, _model.Spents, forStableItems: true);
            Button addStableSpentsItemButton = FindViewById<Button>(Resource.Id.addStableSpentsItemButton);
            addStableSpentsItemButton.Click += (sender, e) => _model.AddNewStableSpent(stableSpentsItemNameTextView.Text);
            ListView occasionalSpentsListView = FindViewById<ListView>(Resource.Id.occasionalSpentsListView);
            occasionalSpentsListView.Adapter = new OccasionalSpentsAdapter(this, _model);
            AutoCompleteTextView occasionalSpentsItemNameTextView = FindViewById<AutoCompleteTextView>(Resource.Id.occasionalSpentsItemNameTextView);
            _model.Spents.NewOccasionalMoneyFlowItemNameChanged += (sender, e) => occasionalSpentsItemNameTextView.Text = _model.Spents.NewOccasionalMoneyFlowItemName;
            occasionalSpentsItemNameTextView.Adapter = new MoneyFlowItemNameSuggestionsAdapter(this, _model.Spents, forStableItems: false);
            Button addOccasionalSpentsItemButton = FindViewById<Button>(Resource.Id.addOccasionalSpentsItemButton);
            addOccasionalSpentsItemButton.Click += (sender, e) => _model.AddNewOccasionalSpent(occasionalSpentsItemNameTextView.Text);
        }

        private void HookModelToResultsTab()
        {
            Spinner reportPeriodSizeSpinner = FindViewById<Spinner>(Resource.Id.reportPeriodSizeSpinner);
            if (_model.Report.CurrentReportPeriodSize == TimeSpan.FromDays(1.0))
                reportPeriodSizeSpinner.SetSelection(0);
            if (_model.Report.CurrentReportPeriodSize == TimeSpan.FromDays(7.0))
                reportPeriodSizeSpinner.SetSelection(1);
            if (_model.Report.CurrentReportPeriodSize == TimeSpan.FromDays(StableMoneyFlowItemModel.AsDaysInMonth))
                reportPeriodSizeSpinner.SetSelection(2);
            if (_model.Report.CurrentReportPeriodSize == TimeSpan.FromDays(StableMoneyFlowItemModel.AsDaysInYear))
                reportPeriodSizeSpinner.SetSelection(3);
            reportPeriodSizeSpinner.ItemSelected += (sender, e) =>
            {
                switch (reportPeriodSizeSpinner.SelectedItemPosition)
                {
                    case 0:
                        _model.Report.CurrentReportPeriodSize = TimeSpan.FromDays(1.0);
                        break;
                    case 1:
                        _model.Report.CurrentReportPeriodSize = TimeSpan.FromDays(7.0);
                        break;
                    case 2:
                        _model.Report.CurrentReportPeriodSize = TimeSpan.FromDays(StableMoneyFlowItemModel.AsDaysInMonth);
                        break;
                    case 3:
                        _model.Report.CurrentReportPeriodSize = TimeSpan.FromDays(StableMoneyFlowItemModel.AsDaysInYear);
                        break;
                }
            };
            Spinner reportPeriodSpinner = FindViewById<Spinner>(Resource.Id.reportPeriodSpinner);
            reportPeriodSpinner.Adapter = new ReportPeriodsAdapter(this, _model);
            reportPeriodSpinner.ItemSelected += (sender, e) => _model.Report.CurrentPeriodReport = _model.Report.PeriodReports.ElementAtOrDefault(reportPeriodSpinner.SelectedItemPosition);
            ListView reportListView = FindViewById<ListView>(Resource.Id.reportListView);
            reportListView.Adapter = new ReportAdapter(this, _model);
        }

        private void Report_CurrentPeriodReportChanged(object sender, EventArgs e)
        {
            PeriodReportModel currentPeriod = _model.Report.CurrentPeriodReport;
            decimal? totalIncomes = currentPeriod == null ? null : (decimal?)currentPeriod.GetTotalIncomes();
            decimal? totalSpents = currentPeriod == null ? null : (decimal?)currentPeriod.GetTotalSpents();
            TextView periodIncomesSummaryTextView = FindViewById<TextView>(Resource.Id.periodIncomesSummaryTextView);
            TextView periodSpentsSummaryTextView = FindViewById<TextView>(Resource.Id.periodSpentsSummaryTextView);
            TextView periodTotalSummaryTextView = FindViewById<TextView>(Resource.Id.periodTotalSummaryTextView);
            periodIncomesSummaryTextView.Text = totalIncomes.HasValue ? totalIncomes.Value.ToString("0.##") : string.Empty;
            periodSpentsSummaryTextView.Text = totalSpents.HasValue ? totalSpents.Value.ToString("0.##") : string.Empty;
            periodTotalSummaryTextView.Text = totalIncomes.HasValue && totalSpents.HasValue ? (totalIncomes - totalSpents).Value.ToString("0.##") : string.Empty;
            if (totalIncomes.HasValue && totalSpents.HasValue)
                periodTotalSummaryTextView.SetTextColor(totalIncomes - totalSpents > 0m ? Resources.GetColor(Resource.Color.incomemarkcolor) : Resources.GetColor(Resource.Color.spentmarkcolor));
        }
    }
}